package org.pine.dictionary.util;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.pine.dictionary.common.IntegerCodeBaseEnum;

/**
 * <p>
 * 整数code枚举-表格字段转换器
 * </p>
 *
 * @author pine
 * @since 2024-05-16
 */
public class IntegerCodeEnumExcelConverter implements Converter<IntegerCodeBaseEnum> {
    public IntegerCodeEnumExcelConverter() {
    }

    public Class<?> supportJavaTypeKey() {
        return IntegerCodeBaseEnum.class;
    }

    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    public WriteCellData<?> convertToExcelData(IntegerCodeBaseEnum value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new WriteCellData<>(value.getDesc());
    }

    public IntegerCodeBaseEnum convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Class<? extends IntegerCodeBaseEnum> cls = (Class<? extends IntegerCodeBaseEnum>) contentProperty.getField().getType();
        if (cellData.getNumberValue() != null) {
            return IntegerCodeBaseEnum.convertToEnum(cellData.getNumberValue().toString(), cls);
        } else {
            return cellData.getStringValue() != null ? IntegerCodeBaseEnum.convertToEnum(cellData.getStringValue(), cls) : null;
        }
    }
}
